package com.mzj.saas.sdk.refund.ali;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.mzj.saas.sdk.refund.vo.AliRefund;

/**
 * 支付宝退款
 * 
 * @author hp
 *
 */
public class AliRefundRequest {

	private final static Logger logger = LoggerFactory.getLogger(AliRefundRequest.class);
	private static final String ALIPAY_GATEWAY_URL = "https://openapi.alipay.com/gateway.do";
	private static final String FORMAT = "json";
	private static final String CHARSET = "UTF-8";
	private static final String SIGN_TYPE = "RSA2";
	
	private AliRefund aliRefund;
	
	public AliRefundRequest(final AliRefund aliRefund) {
		this.aliRefund  = aliRefund;
	}
	
	/**
	 * 获取支付宝客户端对象
	 * 
	 * @return
	 */
	private AlipayClient getAlipayClient() {
		
		if (StringUtils.isBlank(aliRefund.getAppId())) {
			logger.error("AliPayRequest appid is null");
			return null;
		}
		if (StringUtils.isBlank(aliRefund.getPrivateKey())) {
			logger.error("AliPayRequest privateKey is null");
			return null;
		}
		if (StringUtils.isBlank(aliRefund.getPublicKey())) {
			logger.error("AliPayRequest publicKey is null");
			return null;
		}
		
		return new DefaultAlipayClient(ALIPAY_GATEWAY_URL, aliRefund.getAppId(),aliRefund.getPrivateKey(), FORMAT, CHARSET,aliRefund.getPublicKey(), SIGN_TYPE);
	}
	
	 /**
	  * https://opendocs.alipay.com/apis/api_1/alipay.trade.refund
	  * 退款
	  * 退款的途径按照支付途径原路返回，交易超过约定时间（签约时设置的可退款时间）的订单无法进行退款。
                      支付渠道为花呗、余额等退款即时到账。银行卡的退款时间以银行退款时间为准，一般情况下 2 小时内可到账。
                      商家也可以在商家中心（b.alipay.com）中退款。
                     退款是否成功可以根据同步响应的 fund_change 参数来判断，返回值为 Y 则表示退款成功。
                     退款接口会根据外部请求号 out_request_no 幂等返回，因此同一笔交易需要多次部分退款时，必须使用不同的 out_request_no。
	  * @return
	  */
	 public JSONObject tradeRefund() {
		 try {
			 AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();//创建API对应的request类
			 Map<String,String> map = new HashMap<>();
			 if(StringUtils.isNotBlank(aliRefund.getOutTradeNo())) {
				 map.put("out_trade_no", aliRefund.getOutTradeNo());
			 }
			 if(StringUtils.isNotBlank(aliRefund.getTradeNo())){
				 map.put("trade_no", aliRefund.getTradeNo());
			 }
			 map.put("out_request_no", aliRefund.getOutRequestNo());
			 map.put("refund_amount", String.valueOf(aliRefund.getRefundAmount()));
			 String json = JSON.toJSONString(map);
			 request.setBizContent(json);
			 AlipayClient alipayClient = this.getAlipayClient();
			 if(alipayClient == null) {
				 logger.error("[AliRefundRequest tradeRefund] Get AlipayClient Failed!");
				 return null;
			 }
			 AlipayTradeRefundResponse response = alipayClient.execute(request);
			 if(response.isSuccess()) {
				 JSONObject bodyJson = JSONObject.parseObject(response.getBody());
				 String payReponse =  bodyJson.get("alipay_trade_refund_response").toString();
				 JSONObject reponse  = JSONObject.parseObject(payReponse);
				 return reponse;
			 }
			 logger.error("AliRefundRequest----->退款调用失败 result={}",response.getBody());
		 }catch(Exception e) {
			 logger.error("支付宝退款异常" + e.getMessage(),e);
		 }
		 return null;
	 }
	 
	 /**
	  * https://opendocs.alipay.com/apis/api_1/alipay.trade.fastpay.refund.query
	  * 退款查询
	  * @return
	  */
	 public JSONObject refundQuery() {
		 try {
			 AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
			 Map<String,String> map = new HashMap<>();
			 map.put("out_trade_no", aliRefund.getOutTradeNo());
			 map.put("out_request_no", aliRefund.getOutRequestNo());
			 String json = JSON.toJSONString(map);
			 request.setBizContent(json);
			 AlipayClient alipayClient = this.getAlipayClient();
             if(alipayClient == null) {
            	 logger.error("[AliRefundRequest refundQuery] Get AlipayClient Failed!");
				 return null;
			 }
			 AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
			 if(response.isSuccess()){
				 JSONObject bodyJson = JSONObject.parseObject(response.getBody());
				 String payReponse =  bodyJson.get("alipay_trade_fastpay_refund_query_response").toString();
				 JSONObject reponse  = JSONObject.parseObject(payReponse);
				 return reponse;
			 }
			 logger.error("AliRefundRequest----->查询退款调用失败 result={}",response.getBody());
		 }catch(Exception e) {
			 logger.error("查询支付宝退款状态异常" + e.getMessage(),e);
		 }
		 return null;
	 }
	
}
